package com.cratos.xxgram.platf.presetsecret;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.redkale.convert.json.JsonConvert;
import org.redkale.net.http.RestMapping;
import org.redkale.net.http.RestService;
import org.redkale.service.RetResult;
import org.redkale.source.FilterExpress;
import org.redkale.source.FilterFunc;
import org.redkale.source.FilterNode;
import org.redkale.source.Flipper;
import org.redkale.util.AnyValue;
import org.redkale.util.Sheet;
import org.redkale.util.Utility;

import com.cratos.xxgram.platf.base.BaseService;
import com.cratos.xxgram.platf.base.RetCodes;
import com.cratos.xxgram.platf.base.UserInfo;
import com.cratos.xxgram.platf.friend.FriendShip;
import com.cratos.xxgram.platf.message.MessageRecord;
import com.cratos.xxgram.platf.message.NotifyContent.UpdateSecretSetting;

@RestService(name = "presetsecret", comment = "预设密信")
public class PresetsecretRecordService extends BaseService {

	
	@Override
	public void init(AnyValue config) {
		super.init(config);
	}
	
	@RestMapping(name = "addSecretRecord", auth = true, comment = "添加秘信")
	public RetResult addSecretRecord(UserInfo userInfo, SecretRecord bean) {
		int secretrecordid = source.getNumberResult(SecretRecord.class, FilterFunc.MAX, 1_00, "secretrecordid", (FilterNode) null).intValue() + 1;
		bean.setSecretrecordid(secretrecordid);
		bean.setUserid(userInfo.getUserid());
		bean.setCreatetime(System.currentTimeMillis());
		if (bean.getSecret().isEmpty()) return RetCodes.retResult(RetCodes.RET_PARAMS_ILLEGAL);// 参数无效
		source.insert(bean);
		return RetResult.success(bean);
	}
	
	@RestMapping(name = "removeRecord", auth = true, comment = "删除秘信")
	public RetResult removeRecord(UserInfo userInfo, SecretRecord bean) {
		if (bean == null || bean.getSecretrecordid() == 0) return RetCodes.retResult(RetCodes.RET_PARAMS_ILLEGAL);// 参数无效
		
		// 添加配置删除通知
		MessageRecord msg = new MessageRecord();
		msg.setFromid(userInfo.getUserid());
		msg.setMsgtype(UpdateSecretSetting.TYPE);
		msg.setMsgkind(MessageRecord.MSG_KIND_PRIVATE);
		msg.setCreatetime(System.currentTimeMillis());
		msg.setContent(JsonConvert.root().convertTo(UpdateSecretSetting.from(userInfo.getUserid(), UpdateSecretSetting.OP_REMOVE, null)));
		FilterNode node = FilterNode.create("secretrecordid", FilterExpress.EQUAL, bean.getSecretrecordid());
		List<PresetsecretRecord> rows = source.queryList(PresetsecretRecord.class, node);
		
		if (rows != null && rows.size() > 0) {
			rows.forEach(row -> {
				// 发送通知
				MessageRecord record = msg.copy();
				record.setTargetid(row.getFriendid());
				webSocketNode.sendMessage(Utility.ofMap("record", record), row.getFriendid());
			});
		}
		source.delete(PresetsecretRecord.class, node);
		return RetResult.success(source.delete(bean));
	}
	
	@RestMapping(name = "loadSecretRecords", auth = true, comment = "查询密信列表")
	public RetResult loadSecretRecords(UserInfo userInfo, Flipper flipper, SecretRecordBean bean) {
		if (bean == null) bean = new SecretRecordBean();
		bean.setUserid(userInfo.getUserid());
		Sheet<SecretRecord> rs = source.querySheetAsync(SecretRecord.class, flipper, bean).whenComplete((sheet, e) -> {
			Collection<SecretRecord> rows = sheet.getRows();
			rows.forEach(obj -> {
				 FilterNode node = FilterNode.create("secretrecordid", FilterExpress.EQUAL, obj.getSecretrecordid());
                 Number num = source.getNumberResult(PresetsecretRecord.class, FilterFunc.COUNT, 0, "presetsecretid", node);
                 obj.setNum(num.intValue());
			});
		}).join();
		return RetResult.success(rs);
	}
	
	@RestMapping(name = "checkSecretRecord", auth = true, comment = "校验密信是否存在")
	public RetResult checkSecretRecord(UserInfo userInfo, SecretRecordBean bean) {
		if (bean.getSecretrecordid() <= 0 || bean.getSecret() == null || bean.getSecret().isEmpty()) return RetCodes.retResult(RetCodes.RET_PARAMS_ILLEGAL);
		return RetResult.success(source.exists(SecretRecord.class, bean));
	}
	
	@RestMapping(name = "checkExistPresetsecretRecord", auth = true, comment = "校验当前会话密信是否存在")
	public RetResult checkExistPresetsecretRecord(UserInfo userInfo, int friendid) {
		return RetResult.success(source.find(PresetsecretRecord.class, FilterNode.create("friendid", FilterExpress.EQUAL, userInfo.getUserid()).and("userid", FilterExpress.EQUAL, friendid)));
	}
	
	
	@RestMapping(name = "loadAllPresetsecretRecords", auth = true, comment = "查询所有密信成员")
	public RetResult loadAllPresetsecretRecords(UserInfo userInfo, PresetsecretRecordBean bean) {
		//参数无效
		if (bean == null || bean.getSecretrecordid() <= 0) return RetCodes.retResult(RetCodes.RET_PARAMS_ILLEGAL);
		List<PresetsecretRecord> presetsecretRecords = source.queryListAsync(PresetsecretRecord.class, bean).whenComplete((rows, e) -> {
			if (rows != null && !rows.isEmpty()) {
				rows.forEach(obj -> {
					FriendShip friendShip = source.find(FriendShip.class, FilterNode
								.create("userid", FilterExpress.EQUAL, userInfo.getUserid())
								.and("friendid", FilterExpress.EQUAL, obj.getFriendid()));
					if (friendShip != null) {
						friendShip.setFriend(source.find(UserInfo.class, obj.getFriendid()));
						obj.setFriendShip(friendShip);
					}
				});
			}
		}).join();
		return RetResult.success(presetsecretRecords);
	}
	
	@RestMapping(name = "addPresetsecretRecord", auth = true, comment = "添加密信成员")
	public RetResult addPresetsecretRecord(UserInfo userInfo, PresetsecretRecordBean bean)  {
		bean.setUserid(userInfo.getUserid());
		int secretrecordid = bean.getSecretrecordid();
		long now = System.currentTimeMillis();
		int[] friends = bean.getFriendids();
		boolean exist = source.exists(SecretRecord.class, secretrecordid);
		if (!exist || friends == null || friends.length == 0)  return RetCodes.retResult(RetCodes.RET_PARAMS_ILLEGAL);
		Set<PresetsecretRecord> presetsecretRecords = new HashSet<PresetsecretRecord>();
		SecretRecord secretRecord = source.find(SecretRecord.class, secretrecordid);
		// 添加配置通知
		MessageRecord msg = new MessageRecord();
		msg.setFromid(userInfo.getUserid());
		msg.setMsgtype(UpdateSecretSetting.TYPE);
		msg.setMsgkind(MessageRecord.MSG_KIND_PRIVATE);
		msg.setCreatetime(System.currentTimeMillis());
		msg.setContent(JsonConvert.root().convertTo(UpdateSecretSetting.from(userInfo.getUserid(), UpdateSecretSetting.OP_ADD, secretRecord.getSecret())));
		
		for (int i = 0; i < friends.length; i++) {
			int friendid = friends[i];
			source.delete(PresetsecretRecord.class, FilterNode
						.create("friendid", FilterExpress.EQUAL, friendid)
						.and("userid", FilterExpress.EQUAL, userInfo.getUserid()));
			PresetsecretRecord record = new PresetsecretRecord();
			record.setCreatetime(now);
			record.setUserid(userInfo.getUserid());
			record.setSecretrecordid(secretrecordid);
			record.setPresetsecretid(userInfo.getUserid() + "-" + friendid +"-" + secretrecordid);
			record.setFriendid(friendid);
			presetsecretRecords.add(record);
			
			MessageRecord rs = msg.copy();
			rs.setTargetid(friendid);
			// 发送通知
			webSocketNode.sendMessage(Utility.ofMap("record", rs), friendid);
		}
		return RetResult.success(source.insert(presetsecretRecords));
	}
	
	@RestMapping(name = "queryAllPresetsecretRecord", auth = true, comment = "查询所有密信列表")
	public RetResult<Set<PresetsecretRecord>> queryAllPresetsecretRecord(UserInfo userinfo) {
		FilterNode node = FilterNode.create("friendid", FilterExpress.EQUAL, userinfo.getUserid());
		List<PresetsecretRecord> rows = source.queryList(PresetsecretRecord.class, node);
		Set<PresetsecretRecord> set = new HashSet<PresetsecretRecord>();
		rows.forEach(obj -> {
			SecretRecord secretRecord = source.find(SecretRecord.class, obj.getSecretrecordid());
			if (secretRecord != null) {
				obj.setSecret(secretRecord.getSecret());
				set.add(obj);
			}
		});
		return RetResult.success(set);
	}
}
